from bpy.types import Node
import bpy
# 集合管理系统
# 1.物体节点
# 2.集合节点
#   物体节点连上集合节点 即可 自动关联到该集合
#   物体节点从集合节点断开，则取消该关联


class Node_Collection(Node):
    bl_label = '集合'
    bl_icon = 'NONE'
    bl_width_min = 200.0
    bl_width_max = 400.0
    collection: bpy.props.PointerProperty(type=bpy.types.Collection)

    # 节点初始化
    def init(self, context):
        # 不需要新建输出节点
        print("Init")
        self.inputs.new('NodeSocketString', '物体名')
        self.outputs.new('NodeSocketString', '集合名')
        self.width = 280

    def draw_buttons(self, context, layout):
        layout.prop(self, "collection")

    # 节点更新
    def update(self):
        if self.collection:
            for i in self.inputs:
                if i.links:
                    if hasattr(i.links[0].from_node, "object"):
                        o = i.links[0].from_node.object
                        i.default_value = o.name + "xxxxxxxxxxxx" + "object"
                        if o.name not in self.collection.objects:
                            self.collection.objects.link(o)
                    if hasattr(i.links[0].from_node, "collection"):
                        col = i.links[0].from_node.collection
                        i.default_value = col.name + "xxxxxxxxxxxx" + "collection"
                        if col.name not in self.collection.children:
                            self.collection.children.link(col)
        # 节点自动添加输入点 和 自动移除
        inputs = self.inputs[:]
        for i in inputs:
            if i.is_linked:
                continue
            if i.default_value and self.collection:
                name, t = i.default_value.split("xxxxxxxxxxxx")
                if t == "object":
                    if name in bpy.data.objects and name in self.collection.objects:
                        o = bpy.data.objects[name]
                        self.collection.objects.unlink(o)
                if t == "collection":
                    if name in bpy.data.collections and name in self.collection.children:
                        col = bpy.data.collections[name]
                        self.collection.children.unlink(col)
            self.inputs.remove(i)

        self.inputs.new('NodeSocketString', '物体名')
